package com.hsnn.medstgmini.trading.pur.controller;

import java.lang.reflect.Type;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.dict.model.DicSys;
import com.hsnn.medstgmini.base.std.model.HospInfo;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.trading.catalog.model.PurHospcatalog;
import com.hsnn.medstgmini.trading.pur.model.form.PurPlanForm;
import com.hsnn.medstgmini.trading.pur.service.PurPurPlanManager;
import com.hsnn.medstgmini.util.DicSysUtil;
import com.hsnn.medstgmini.util.Pagination;
import com.hsnn.medstgmini.util.ParseNumber;
import com.hsnn.medstgmini.validator.ValidatorUtil;
/**
 * 
 *@category 医疗机构制定购物计划
 *@author 邱磊
 *@date 2015年7月8日 下午5:02:43
 */
@Controller
@RequestMapping("/purPurPlanController")
public class PurPurPlanController {
	private final static Logger log = Logger.getLogger(PurPurPlanController.class);
	
	@Autowired
	private HttpServletRequest request;
	
	@Autowired
	private PurPurPlanManager manager;
	
	@Value("#{sysProp['system.isSetPlanPrice']}")
	private boolean isSetPlanPrice;
	
	@Value("#{sysProp['system.bakBatchBuy']}")
	private boolean bakBatchBuy;
	
	@Value("#{sysProp['system.isHisRecordAmount']}")
	private boolean isHisRecordAmount ;
	
	/**
	 * 
	 *@category 跳到制定制计划页面（医疗机构）
	 *@author 邱磊
	 *@date 2015年7月8日 下午5:13:42
	 *@return
	 */
	@RequestMapping("/toPurPlanSelect")
	public String toPurPlanSelect(){
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		String hospCode = ((HospInfo) user.getInfo()).getHospCode();
		request.setAttribute("count", manager.getPlanCount(hospCode));
		List<DicSys> list = DicSysUtil.getDicListByClassCode(Constants.PRO_METHOD);
		if(list != null){
			for(int i=0;i<list.size();i++){
				if( Constants.GOODS_SOURCE_BJBX == Integer.valueOf(list.get(i).getDicCode()) && StringUtils.isBlank(list.get(i).getDicName())){
					list.get(i).setDicName("不竞不限");
				}
			}
		}
		request.setAttribute("list", list);
		request.setAttribute("isSetPlanPrice", isSetPlanPrice);
		request.setAttribute("bakBatchBuy", bakBatchBuy);
		return "/pro/pur/purPlanSelect";
	}
	/**
	 * 
	 *@category 获取勾选制定计划列表（医疗机构）
	 *@author 邱磊
	 *@date 2015年7月8日 下午5:20:33
	 *@param form
	 *@return
	 */
	@RequestMapping("/getPurHospCatalogList")
	@ResponseBody
	public Pagination getPurHospCatalogList(PurPlanForm form){
		log.info("获取勾选制定计划列表"+form);
		Pagination page = new Pagination(request);
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		String hospCode = ((HospInfo) user.getInfo()).getHospCode();
		form.setJoinPlanUser(user.getId());
		form.setHospCode(hospCode);
		page.setForm(form);
		return manager.getPurHospCatalogList(page);
	}
	/**
	 * 
	 *@category 加入计划（医疗机构）
	 *@author 邱磊
	 *@date 2015年7月8日 下午6:11:21
	 *@param array
	 *@return
	 */
	@RequestMapping("/batchJoinPlan")
	@ResponseBody
	public Pagination batchJoinPlan(String array){
		log.info("加入计划（医疗机构）"+array);
		Pagination page = new Pagination(request);
		if (array != null && !"".equals(array)) {
			Gson gson = new Gson();
			Type type = new TypeToken<List<PurPlanForm>>() {
			}.getType();
			List<PurPlanForm> list = gson.fromJson(array, type);
			SysUser user = (SysUser) request.getSession().getAttribute(
					Constants.USERINFO);
			String hospId = ((HospInfo) user.getInfo()).getHospId();
			if (list != null && !list.isEmpty()) {
				for (PurPlanForm dp : list) {
					if (!ValidatorUtil.validatePositiveInteger(dp.getBuyNum())){
						page.setSuccess(false);
						page.setMsg("请正确填写采购数量！");
						return page;
					}
					if (isSetPlanPrice){
						if (StringUtils.isNotBlank(dp.getProPrice())){
							if (!ValidatorUtil.isDouble(dp.getProPrice())){
								page.setSuccess(false);
								page.setMsg("\"" + dp.getDrugName() + "\"采购价格式不正确！");
								return page;
							} else {
								if (ParseNumber.toDouble(dp.getProPrice()) > ParseNumber.toDouble(dp.getProLimitPrice())){
									page.setSuccess(false);
									page.setMsg("\"" +dp.getDrugName() + "\"采购价不能大于采购限价！");
									return page;
								}
							}
						} else {
							page.setSuccess(false);
							page.setMsg("\"" +dp.getDrugName() + "\"采购价不能为空！");
							return page;
						}
					} 
					PurHospcatalog data = manager.getCatalogInfoById(dp.getHospProCatId());
					if (null != data){
						if (StringUtils.isBlank(data.getDelCompCode())){
							page.setSuccess(false);
							page.setMsg("请在已勾选商品目录处为您勾选的药品设置配送企业！");
							return page;
						}
						dp.setCatalogInfo(data);
					} else {
						page.setSuccess(false);
						page.setMsg("您勾选的计划有误，请联系管理员！");
						return page;
					}
					dp.setJoinPlanUser(user.getId());
					dp.setHospId(hospId);
				}
				try {
					manager.batchJoinPlan(list);
					String hospCode = ((HospInfo) user.getInfo()).getHospCode();
					page.getConditions().put("count", manager.getPlanCount(hospCode)+"");
					page.setSuccess(true);
				} catch (Exception e) {
					e.printStackTrace();
					page.setSuccess(false);
					page.setMsg("操作失败，请联系管理员！");
					return page;
				}
			}
		}
		return page;
	}
	/**
	 * 
	 *@category 跳向购物计划查看页面（医疗机构）
	 *@author 邱磊
	 *@date 2015年7月8日 下午7:27:41
	 *@return
	 */
	@RequestMapping("/toSeePurPlan")
	public String toSeePurPlan(Model model,PurPlanForm form){
		log.info("[医疗机构]跳向购物计划查看页面:"+form);
		Pagination page = new Pagination(request);
		SysUser user = (SysUser) request.getSession().getAttribute(
				Constants.USERINFO);
		form.setMain(user.getMain());
		String hospCode = ((HospInfo) user.getInfo()).getHospCode();
		form.setJoinPlanUser(user.getId());
		form.setHospId(hospCode);
		page.setForm(form);
		page = manager.getPurPlanDataList(page);
		List<DicSys> list = DicSysUtil.getDicListByClassCode(Constants.PRO_METHOD);
		if(list != null){
			for(int i=0;i<list.size();i++){
				if( Constants.GOODS_SOURCE_BJBX == Integer.valueOf(list.get(i).getDicCode()) && StringUtils.isBlank(list.get(i).getDicName())){
					list.get(i).setDicName("不竞不限");
				}
			}
		}
		request.setAttribute("list", list);
		request.setAttribute("bakBatchBuy", bakBatchBuy);
		model.addAttribute("allPrice", page.getConditions().get("allPrice"));
		request.setAttribute("isSetPlanPrice", isSetPlanPrice);
		//是否给出备案金额提示
		request.setAttribute("isHisRecordAmount", isHisRecordAmount);
		return "/pro/pur/purPlanList";
	}
	/**
	 * 
	 *@category 获取已勾选购物计划数据（医疗机构）
	 *@author 邱磊
	 *@date 2015年7月8日 下午7:44:37
	 *@param form
	 *@return
	 */
	@RequestMapping("/getPurPlanDataList")
	@ResponseBody
	public Pagination getPurPlanDataList(Model model,PurPlanForm form){
		log.info("[医疗机构]获取已勾选购物计划数据："+form);
		Pagination page = new Pagination();
		SysUser user = (SysUser) request.getSession().getAttribute(
				Constants.USERINFO);
		form.setMain(user.getMain());
		String hospCode = ((HospInfo) user.getInfo()).getHospCode();
		form.setJoinPlanUser(user.getId());
		form.setHospId(hospCode);
		page.setForm(form);
		page = manager.getPurPlanDataList(page);
		model.addAttribute("allPriceAmount", page.getConditions().get("allPrice"));
		return page;
	}
	/**
	 * 
	 *@category 删除购物计划（医疗机构）
	 *@author 邱磊
	 *@date 2015年7月8日 下午7:49:31
	 *@param array
	 *@return
	 */
	@RequestMapping("/batchDelete")
	@ResponseBody
	public Pagination batchDelete(String array){
		log.info("删除购物计划（医疗机构）"+array);
		Pagination page = new Pagination(request);
		if (array != null && !"".equals(array)) {
			Gson gson = new Gson();
			Type type = new TypeToken<List<PurPlanForm>>() {
			}.getType();
			List<PurPlanForm> list = gson.fromJson(array, type);
			if (list != null && !list.isEmpty()) {
				try {
					manager.batchDelete(list);
					page.setSuccess(true);
				} catch (Exception e) {
					e.printStackTrace();
					page.setSuccess(false);
					page.setMsg("操作失败，请联系管理员！");
					return page;
				}
			}
		}
		return page;
	}
	/**
	 * 
	 *@category 保存购物计划（医疗机构）
	 *@author 邱磊
	 *@date 2015年7月8日 下午7:49:31
	 *@param array
	 *@return
	 */
	@RequestMapping("/batchSave")
	@ResponseBody
	public Pagination batchSave(String array){
		log.info("保存购物计划（医疗机构）"+array);
		Pagination page = new Pagination(request);
		if (array != null && !"".equals(array)) {
			Gson gson = new Gson();
			Type type = new TypeToken<List<PurPlanForm>>() {
			}.getType();
			List<PurPlanForm> list = gson.fromJson(array, type);
			if (list != null && !list.isEmpty()) {
				try {
					SysUser user = (SysUser) request.getSession().getAttribute(
							Constants.USERINFO);
					for (PurPlanForm dp : list) {
						dp.setUpdUser(user.getId());
						if (!ValidatorUtil.validatePositiveInteger(dp.getBuyNum())){
							page.setSuccess(false);
							page.setMsg("请正确填写采购数量！");
							return page;
						}
						if (isSetPlanPrice){
							if (StringUtils.isNotBlank(dp.getProPrice())){
								if (!ValidatorUtil.isDouble(dp.getProPrice())){
									page.setSuccess(false);
									page.setMsg("\"" + dp.getDrugName() + "\"采购价格式不正确！");
									return page;
								} else {
									if (ParseNumber.toDouble(dp.getProPrice()) > ParseNumber.toDouble(dp.getProLimitPrice())){
										page.setSuccess(false);
										page.setMsg("\"" +dp.getDrugName() + "\"采购价不能大于采购限价！");
										return page;
									}
								}
							} else {
								page.setSuccess(false);
								page.setMsg("\"" +dp.getDrugName() + "\"采购价不能为空！");
								return page;
							}
						} 
					}
					manager.batchSave(list);
					page.setSuccess(true);
				} catch (Exception e) {
					e.printStackTrace();
					page.setSuccess(false);
					page.setMsg("操作失败，请联系管理员！");
					return page;
				}
			}
		}
		return page;
	}
	
	
	/**
	 * 
	 *@category 获取医院备案采购历史交易金额
	 *@author yxc
	 *@date 2016年1月13日09:36:21
	 *@return
	 */
	@RequestMapping("/getHisRecordAmount")
	@ResponseBody
	public Pagination getHisRecordAmount(){
		Pagination page = new Pagination();
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		String hospCode = ((HospInfo) user.getInfo()).getHospCode();
		page.getConditions().put("hospCode", hospCode);
		page.getConditions().put("userId", user.getId());
		manager.getHisRecordAmount(page);
		return page;
	}
	
	
}
